package com.baosan.school.interceptor;

import com.baosan.school.common.RedisUtil;
import com.baosan.school.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: school
 * @description:
 * @author: heping
 * @create: 2022-01-16 07:46
 */
@Component
public class WebInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtil redisUtil;
    /**
     * 控制器方法调用之前会进行
     * 和上面的Filter一样，继承的某些接口方法中也加了default关键字，可以不用重写，这里为了演示就都写了
     *
     * @param request
     * @param response
     * @param handler
     * @return true就是选择可以调用后面的方法  如果后续有ControllerAdvice的话会去执行对应的方法等。
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        //得到请求的url
        String url = request.getRequestURI();
        if(!url.contains("/login")){
            String token = request.getHeader("token") ;
            String userId =  request.getHeader("userId");
            if(request.getHeader("token")!=""&&request.getHeader("token")!=""){
                Object redisToken = redisUtil.get(userId);
                if(redisToken!=null&&token.equals(redisToken)){
                    return true;
                }
            }
        }
        return false;
    }

}

